package mju.cn.oneweek;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/**
 * @program: java-ee_31
 * @description:
 * @author: HP
 * @time: 2020/9/18 15:46
 */
public class ReflectServiceImpl2 {
    private String name;
    public void RefilectServiceImpl2(String name){
        this.name=name;
    }

    public void sayHello(String name){
        System.out.println("Hello "+name);
    }



//    public ReflectServiceImpl2 getInstance()  {
//        ReflectServiceImpl2 object = null;
//        try {
//            object =(ReflectServiceImpl2)Class.forName("mju.cn.ReflectServiceImpl2").getConstructor(String.class).newInstance("张三");
//        } catch (InstantiationException e) {
//            e.printStackTrace();
//        } catch (IllegalAccessException e) {
//            e.printStackTrace();
//        } catch (ClassNotFoundException e) {
//            e.printStackTrace();
//        } catch (NoSuchMethodException e) {
//            e.printStackTrace();
//        } catch (InvocationTargetException e) {
//            e.printStackTrace();
//        }
//        return object;
//    }

    public static void main(String[] args) {
        ReflectServiceImpl2 re=new ReflectServiceImpl2();
        System.out.println(re.reflect());
    }

    public Object reflectMethod(){
        Object returnObj =null;
        ReflectServiceImpl2 target = new ReflectServiceImpl2();
        try {
            Method method =ReflectServiceImpl2.class.getMethod("sayHello", String.class);
            returnObj=method.invoke(target,"张三");

        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
        return returnObj;
    }

    //实例：
    public  Object reflect(){
        ReflectServiceImpl2 object = null;
        try{
            object=(ReflectServiceImpl2)Class.forName("mju.cn.oneweek.ReflectServiceImpl2").newInstance();//生成一个对象，全限定名
            Method method= object.getClass().getMethod("sayHello", String.class);
            method.invoke(object,"张三");
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
        return object;
    }
}
